package com.mac.intellect_flow.framework.service;

import com.mac.intellect_flow.constant.CommonConstant;
import com.mac.intellect_flow.enums.ResultCodeEnum;
import com.mac.intellect_flow.except.ServiceException;
import com.mac.intellect_flow.framework.dto.SysUserDto;
import com.mac.intellect_flow.framework.security.context.AuthenticationContextHolder;
import com.mac.intellect_flow.redis.util.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.Authentication;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

/**
 * 登录密码方法
 * 
 * @author mac
 */
@Component
public class SysPasswordService {
    @Autowired
    private RedisUtil redisCache;

    @Value(value = "${user.password.maxRetryCount:6}")
    private int maxRetryCount;

    @Value(value = "${user.password.lockTime:5}")
    private int lockTime;

    @Autowired
    private BCryptPasswordEncoder passwordEncoder;

    /**
     * 登录账户密码错误次数缓存键名
     * 
     * @param username 用户名
     * @return 缓存键key
     */
    private String getCacheKey(String username) {
        return CommonConstant.PWD_ERR_CNT_KEY + username;
    }

    public void validate(SysUserDto user) {
        Authentication usernamePasswordAuthenticationToken = AuthenticationContextHolder.getContext();
        String username = usernamePasswordAuthenticationToken.getName();
        String password = usernamePasswordAuthenticationToken.getCredentials().toString();

        Integer retryCount = redisCache.getCacheObject(getCacheKey(username));

        if (retryCount == null) {
            retryCount = 0;
        }

        if (retryCount >= maxRetryCount) {
            throw new ServiceException(ResultCodeEnum.INTERNAL_SERVER_ERROR.getCode(), "密码输入错误次数超过" +maxRetryCount+"次，会锁"+lockTime+"分钟");
        }

        if (!matches(user, password)) {
            retryCount = retryCount + 1;
            redisCache.setCacheObject(getCacheKey(username), retryCount, lockTime, TimeUnit.MINUTES);
            throw new ServiceException(ResultCodeEnum.INTERNAL_SERVER_ERROR.getCode(),"密码错误"+retryCount+"次");
        } else {
            clearLoginRecordCache(username);
        }
    }

    public boolean matches(SysUserDto user, String rawPassword) {
        return passwordEncoder.matches(rawPassword, user.getPassword());
    }

    public void clearLoginRecordCache(String loginName) {
        if (redisCache.hasKey(getCacheKey(loginName))) {
            redisCache.deleteObject(getCacheKey(loginName));
        }
    }
}
